<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class MealCate extends Model
{
    const CREATED_AT = 'insert_time';
    const UPDATED_AT = 'update_time';
    /**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'lexiang_meal_cate';

    protected $primaryKey = 'cate_id';

    public $timestamps = false;

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = ['cate_name','cate_price','cate_desc','cate_imgs','shops_id','sort_id','cate_status','insert_time'];

    public function createCate($post) {
        $nowTime = time();
        $this_ = $this;
        if($se = $this_->where('cate_id',$post['cate_id'])->first()){
            $this_ = $se;
        }
        $this_->cate_name = $post['cate_name'];
        $this_->cate_price = $post['cate_price'];
        $this_->cate_desc = $post['cate_desc'] ?? '';
        if(isset($post['cate_img'])){
            $this_->cate_imgs = $post['cate_img'];
        }
        $this_->shops_id = $post['shop_id'];
        $this_->sort_id = $post['sort_id'] ?? 5;
        $this_->cate_status = $post['cate_status'] ?? 1;
        $this_->insert_time = $nowTime;
        if($this_->save()){
            return true;
        }else{
            return false;
        }
    }

    public static function shopCateList($shopid,$page=15)
    {
    	return MealCate::leftJoin('lexiang_meal_shop','lexiang_meal_cate.shops_id','=','lexiang_meal_shop.shop_id')
    	->where('lexiang_meal_cate.shops_id',$shopid)
    	->orderBy('lexiang_meal_cate.insert_time','desc')
    	->selectRaw('lexiang_meal_cate.*,null as sort_name')
    	->paginate($page,['shopid','order-page','extract-page'],'cate-page');
    }

    public function getCateImgsAttribute($v){
        return "https://jiashilexiang.oss-cn-beijing.aliyuncs.com/MealCateImgs".$v;
    }

    public function getSortNameAttribute($v)
    {
        return MealSort::where('sort_id',$this->sort_id)->value('sort_name') ?? '未知';
    }
}
